//
//  FZHomeViewModel.swift
//  MyWeiBo
//
//  Created by fangzhengwei on 2017/3/30.
//  Copyright © 2017年 fangzhengwei. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
class FZHomeViewModel: NSObject {
//    since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//    max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    lazy var statusArr : [FZStatusViewModel] = [FZStatusViewModel]()
    
    func sendBlogAction(accessToken: String , status : String,pics :[UIImage],callBack:@escaping (Bool)->()) {

       FZNetworkTools.sharedTools.sendLabelPicsBlog(accessToken: accessToken, status: status, pics: pics) { (reponse, error) in
        
        if error != nil{
            callBack(false)
            SVProgressHUD.showError(withStatus: "网络异常\(error)")
         }
          callBack(true)
          SVProgressHUD.showSuccess(withStatus: "发布成功")
    }
        
  }
    func sendBlogAction(accessToken: String , status : String,callBack:@escaping (Bool)->()) {
        
        FZNetworkTools.sharedTools.sendLabelBlog(accessToken: accessToken, status: status) { (reponse, error) in
            
            if error != nil{
                callBack(false)
                print("网络异常\(error)")
            }
            callBack(true)
            
            SVProgressHUD.showSuccess(withStatus: "发布成功")
        }
        
        
    }
    
    let group = DispatchGroup()
    
    fileprivate func downLoadImgData(UrlStr : String) {
      
      group.enter()
      SDWebImageManager.shared().loadImage(with: URL(string : UrlStr), options: [], progress: nil, completed: { (img, data, error, _, _, _) in
        
        if error != nil {
            return
        }
        self.group.leave()
        
      })
    }
    
  
    func loadHomeViewModel(isUpReload : Bool, callBack:@escaping (Bool,String)->()) {
        var maxId : Int64 = 0
        var sinceId : Int64 = 0

        if isUpReload {
            
             maxId = statusArr.last?.statusModel?.id ?? 0
            
            if maxId > 0 {
                maxId -= 1
            }
            
        }else{
            sinceId = statusArr.first?.statusModel?.id ?? 0
        }
       
        if let accessTok = FZUserViewModel.sharedUser.useraccount?.access_token {
            
            FZNetworkTools.sharedTools.loadHomeData(accessToken: accessTok,maxId: maxId, sinceId :sinceId, finishClouse: { (response, error) in
                
                var message = "没有加载到最新微博数据"
                
                if error != nil{
                    
                    print("网络异常\(error)")
                    callBack(false,message)
                    return
                }
                
                guard let res = response else{
                    print("异常")
                    callBack(false,message)
                    return
                }
                
                
                let status = (res as! [String : Any])["statuses"] as! [[String : Any]]
                
                let homeArray = NSArray.yy_modelArray(with: FZStatusModel.self, json: status)
                
                if homeArray == nil{
                    return
                }
                
                var homeArr : [FZStatusViewModel] = [FZStatusViewModel]()
                
                for items in (homeArray as? [FZStatusModel])!{
                  
                    let statusViewModel = FZStatusViewModel()
                    statusViewModel.statusModel = items
                    homeArr.append(statusViewModel)
                    
                    if items.pic_urls?.count == 1 {
                        //原创微博
                        if let urlStr = items.pic_urls?.first?.thumbnail_pic {
                            self.downLoadImgData(UrlStr: urlStr)
                        }
                    }
                    
                    if items.retweeted_status?.pic_urls?.count == 1 {
                        //转发微博
                        if let urlStr = items.retweeted_status?.pic_urls?.first?.thumbnail_pic {
                            
                            self.downLoadImgData(UrlStr: urlStr)
                        }

                    }
                }
                
                if isUpReload {
                    
                    self.statusArr.append(contentsOf: homeArr)
                    
                }else{
                    self.statusArr.insert(contentsOf: homeArr, at: 0)
                    
                }
                
                if homeArr.count > 0 {
                    
                    message = "加载到\(homeArr.count)条最新微博"
                }
                
                
                self.group.notify(queue: DispatchQueue.main) {
                    
                    callBack(true,message)
                }

            })
            
        }
    }
    
}
